import Vue from 'vue'
import Element from 'element-ui'
import md5 from 'js-md5'
import VueAxios from 'vue-axios'

import learunComponents from './components' // Internationalization

import axios from './router/axios'
import router from './router'
import Permission from './permission' // 权限
import UseStore, { store, storeOptions } from './store'
import i18n from './lang' // Internationalization
import App from './App'

import Mixin from './mixins/base'

import './error' // 日志
import './cache' //页面缓冲
import './styles/common.scss'

// 模块列表
import modules from './modules'




export default {
    registerModule(module) {
        if (module) modules.push(...module)
    },
    use:async ({ urls,website }) => {
        // 加载相关url地址
        Object.keys(urls).forEach(key => {
            Vue.prototype[key] = urls[key]
            window[`$${key}`] = urls[key]
        })
        //注册全局组件

        Vue.use(learunComponents)

        Vue.mixin(Mixin())

        // md5

        Vue.prototype.$md5 = md5;
        Vue.config.productionTip = process.env.NODE_ENV !== 'development'
    
        Vue.use(VueAxios, axios)
        // 加载饿了么框架
        Vue.use(Element)
        
        if(window){
            window.$axios = axios
        }


        const routes = []
        modules.forEach(m=>{
            // 注入路由信息
            m.routes && routes.push(...m.routes)
            // 注入状态信息
            m.store && (storeOptions.modules[m.module.code] = m.store)
            // 添加全局组件
            m.components && m.components.forEach(com=>{
                Vue.component(com.name, com.component)
            })

        })
        // 使用状态
        UseStore()

        
        // 系统属性
        let system = {
            modules: modules.map(m => m.module),
            webconfig:website
        }

        store.dispatch('app/init', { system })
        store.commit('SET_TAGWEL', website.fistPage)// 设置首页

       

        // 注入路由信息
        const myRouter = router.use({views:routes,store})
        Object.keys(Permission).forEach(key => {
            myRouter[key](Permission[key])
        })
        Vue.use(myRouter)
        window.$router = myRouter       
        
        

        await  window.$awaitWraper(store.dispatch("language/type/getList"))
        // 动态加载多语言
        const mainLanguage = store.getters.appConfig.language.mainType
        const nowLanguage= store.getters.appConfig.language.type
        if(mainLanguage != nowLanguage){
            const lgMapping = await window.$awaitWraper(window.$api.language.mapping.getList(mainLanguage,nowLanguage))
            if(lgMapping){
                i18n.setLocaleMessage('learun', Object.assign(lgMapping))
            }
        }

        //Vue.config.performance = true;
        new Vue({
            router:myRouter,
            store,
            i18n,
            render: h => h(App)
        }).$mount('#app')
    }
}